(function (wnd) {
    "use strict";
    var errorLogUrl = window.location.protocol + '//developers.devopen.layabox.com/api/errorLog';
    wnd.LayaStruct = (function () {
        function LayaStruct() {
        }

        LayaStruct.getUserStruct = function () {
            return {
                SP_UID: "",
                SP: "",
                NICKNAME: "",
                AVTOR_URL: "",
                DEV_OS: "",
                DEV_OS_VER: "",
                DEV_IMEI: "",
                DEV_IMSI: "",
                DEV_MAC: "",
                SP_TOKEN: "",
                IP: "",
                ACCESS_TOKEN: "",
                GAME_ID: "",
                IS_VIP: "",
                CITY: "",
                SEX: "",
                PROVINCE: "",
                COUNTRY: "",
                HEADIMG: "",
                DEV_MOBILE: "",
                EMAIL: "",
                EQUIPMENT_NUM: "",
                SP_NAME: ""
            }
        };
        LayaStruct.getLoginStruct = function () {
            return {
                spuid: "",
                sptoken: "",
                userId: "",
                typeId: "",
                sp: "",
                nickName: "",
                email: "",
                equipmentNum: "",
                mobile: "",
                headimg: "",
                country: "",
                province: "",
                city: "",
                language: "",
                isvip: ""
            }
        };
        LayaStruct.spLoginInfo = function () {
            return {
                "result": "",
                "desc": "",
                "nickName": "",
                "avatarUrl": "",
                "sessionKey": "",
                "spuid": "",
                "sex": ""
            }
        };
        return LayaStruct;
    })();
    wnd.LayaMakerMarket = (function () {
        function LayaMakerMarket() {
            this.layaStorage = new LayaStorageH5('Storage');
			this.loginCallBack = null;
            this.rewardedVideoAd = null;
            this.ADObj = {};
            this.reportedGameDataCache=[];
        }
        LayaMakerMarket.instance = null;
        LayaMakerMarket.getInstance = function () {
            if (LayaMakerMarket.instance == null) {
                wnd.LBMH5 = LayaMakerMarket.instance = new LayaMakerMarket();
            }
            return LayaMakerMarket.instance;
        };
        var __proto = LayaMakerMarket.prototype;
        __proto.login = function (callback) {
			//登录完成回调
			LBMH5.loginCallBack = callback;
			//微信环境下进行微信登录
			if(LayaCommon.checkWeiXin()){
				this.wxLogin();
			}
        };
		
		//微信检测是否已经登录过
		__proto.wxLogin = function (){
			
			wx.checkSession({
				success: function(){
					//session 未过期，并且在本生命周期一直有效
					console.log('checkSession ok');
					var extParams = '';
					var userInfo = LBMH5.layaStorage.getItem('minigame_userinfo');
					if (userInfo != null){
						console.log('userinfo ok');
						LBMH5.loginCallBack && LBMH5.loginCallBack(1,userInfo);
					}else{
						LBMH5.sessionExpired()
					}
				},
				fail: function(){
					LBMH5.sessionExpired();				
				}
			});
		}
		
		//微信没有登录过进行登录流程
		__proto.sessionExpired = function (){
			//登录态过期
			console.log('checkSession fail');
			wx.login({
			  success: function(dat){
				//session 未过期，并且在本生命周期一直有效
				console.log('login ok' + JSON.stringify(dat));
                // dat.code
				LBMH5.authCodeResult(dat);
			  },
			  fail: function(res){
				//登录失败
				console.log('login fail');
				LBMH5.loginCallBack && LBMH5.loginCallBack(-1);
			  }
			}) //重新登录
		}
		
		//微信登录成功获取用户信息
		__proto.authCodeResult = function (dat)
		{
			var extParams = '';
			wx.getUserInfo({
				success: function(dat1){
					//获得用户信息成功
					console.log('getUserInfo ok' + JSON.stringify(dat1));
					LBMH5.layaStorage.setItem('minigame_userinfo', JSON.stringify(dat1.userInfo));
					LBMH5.loginCallBack && LBMH5.loginCallBack(1,dat1.userInfo);
				},
				fail: function(res){
					//获得用户信息失败
					console.log('getUserInfo fail' + res.errMsg);
					LBMH5.loginCallBack && LBMH5.loginCallBack(-2);
				}				
			});
		}

        //创建视频广告
        __proto.createVideoAD = function (adUnitId) {
            if(LayaCommon.checkWeiXin()){
                LBMH5.ADObj[adUnitId] = wx.createRewardedVideoAd({"adUnitId":adUnitId});
                return LBMH5.ADObj[adUnitId];
            }
        }

        //显示奖励式视频广告
        __proto.showADVideo = function (adUnitId,callback) {
            if(LayaCommon.checkWeiXin()){
                var adobj = LBMH5.ADObj[adUnitId];
                var _callback = callback;
                if(!adobj){
                    //创建广告
                    adobj = LBMH5.createVideoAD(adUnitId);
                }
                //加载广告
                adobj.load().then(function(){
                    //广告加载成功显示广告
                    adobj.show();
                }).catch(function(err){
                    //拉取广告失败
                    console.log(err.errMsg);
                    adobj.destory && adobj.destory();
                    _callback && _callback(-1,err);
                })
                //监听广告关闭
                adobj.onClose(function(status){
                    if(status && status.isEnded || status == undefined){
                        console.log('观看完成发送奖励')
                       _callback && _callback(1);
                    }else{
                        console.log('取消')
                        _callback && _callback(0);
                    }
                   
                    adobj.offClose();
                    adobj.offError();
                    adobj.offLoad();
                });
            }
        }

        //创建横幅广告
        __proto.createBannerAD = function (adUnitId, style) {
            if(LayaCommon.checkWeiXin()){
                LBMH5.ADObj[adUnitId] = wx.createBannerAd({"adUnitId":adUnitId,"style":style});
                return LBMH5.ADObj[adUnitId];
            }
        }

        //显示横幅广告
        __proto.showADBanner = function (adUnitId, style, destroy, callback) {
            (destroy===void 0)&& (destroy=false);
            var _callback = callback;
            var adobj = LBMH5.ADObj[adUnitId];
            if(!adobj){
                adobj = LBMH5.createBannerAD(adUnitId,style);
            }
            else if(destroy){
                adobj.destory();
                adobj = LBMH5.createBannerAD(adUnitId,style);
            }

            adobj.onError(function(err){
                console.log(err);
                _callback && _callback(0);
            })
            adobj.onLoad(function(){
                console.log('banner 广告加载成功');
                _callback && _callback(1);
            })
            adobj.show();
            return adobj;
        }
        
        //隐藏横幅广告
        __proto.hideADBanner = function (adUnitId) {
            var adobj = LBMH5.ADObj[adUnitId];
            if(adobj){
                adobj.offError();
                adobj.offLoad();
                adobj.hide();
            }
        }
		
		__proto.getWXGroupGameData = function (_shareTicket, _keyList, callback){
			var _callback = callback;
			wx.getGroupCloudStorage({
				shareTicket:_shareTicket,
				keyList:_keyList,
				success:function(res){
					console.log("----------------getGroupCloudStorage-------------ok-----------");
					if(res.data)
					{
						console.log(res.data);
                        _callback && _callback(1,res.data);
					}
				},
				fail:function(data){
					console.log("------------getGroupCloudStorage--------------fail-------");
					console.log(data);
                    _callback && _callback(0)
				}
			})
		}

        //获取微信上报数据
        __proto.getWXGameData = function (_keyList, callback) {
            var _callback = callback;
            wx.getFriendCloudStorage({
				keyList:_keyList,
				success:function(res){
					console.log("----------------getFriendUserGameData-------------ok-----------");
					if(res.data)
					{
						console.log(res.data);
                        _callback && _callback(1,res.data);
					}
				},
				fail:function(data){
					console.log("------------getFriendUserGameData--------------fail-------");
					console.log(data);
                    _callback && _callback(0)
				}
			});
        }
		
		__proto.getWXUserInfo = function (_openIDs, callback) {
			var _callback = callback;
			wx.getUserInfo({
				openIdList: _openIDs,
				lang: 'zh_CN',
				success: function(res){
					console.log('success', res.data)
					_callback && _callback(1,res.data);
				},
				fail: function(res){
					console.log('fail', res)
					_callback && _callback(0);
				}
			})
		}
		
		//获取当前用户微信上报数据
		__proto.getSelfWXGameData = function (_keyList, callback) {
			var _callback = callback;
			wx.getUserCloudStorage({
				keyList:_keyList,
				success:function(res){
					console.log("----------------getUserCloudStorage--------------ok----------");
                    var kvDataList = res.KVDataList;
					if(kvDataList.length)
					{
                        var obj = JSON.parse(kvDataList[0].value);
                        _callback && _callback(1, parseInt(obj.wxgame.value1));
					}else{
						_callback && _callback(1, 0);
					}
				},
				fail:function(data){
					console.log("------------getUserCloudStorage--------------fail-------");
					console.log(data);
                    _callback && _callback(0)
				}
			})
		}

        //微信数据上报
        __proto.reportedWXGameData = function (key, value, callback) {
            var _callback = callback;
            var kvDataList = [];
			var _key = key + '';
			var _value = value;
			var singleData = LBMH5.reportedGameDataCache[key];
			if (!singleData){
				singleData = {};
                singleData.wxgame = {};
				singleData.wxgame.value1 = value;
				singleData.wxgame.update_time = Math.floor(Date.now()/1000);
				LBMH5.reportedGameDataCache[key] = singleData;
			}else{
                singleData.wxgame.value1 = value;
                singleData.wxgame.update_time = Math.floor(Date.now()/1000);
				LBMH5.reportedGameDataCache[key] = singleData;
			}
			kvDataList.push({"key":key,"value":JSON.stringify(singleData)})
			
            wx.setUserCloudStorage({
                "KVDataList":kvDataList,
                "success":function(e){
                    console.log('-----success:' + JSON.stringify(e));
                    _callback && _callback(1);
                },
                "fail":function(e){
                    console.log('-----fail:' + JSON.stringify(e));
                    _callback && _callback(0);
                },
                "complete":function(e){
                    console.log('-----complete:' + JSON.stringify(e));
                }
            });
        }

        //微信 主域向子域发消息
        __proto.postMessage = function (data) {
            wx.postMessage(data);
        }

        //微信 子域监听主域发消息
        __proto.onMessage = function (callback) {
            var _callback = callback;
            wx.onMessage(function(data){
                _callback && _callback(data);
            })
        }

        //分享
        __proto.sendShare = function (title, image_url, share_param, callback, canvas, isInit){
            if(LayaCommon.checkWeiXin()){
                var cfg = {};
                cfg.title = title;
                if(canvas){
                    var _callback = callback;
                    canvas.toTempFilePath({
                        x: 0,
                        y: 0,
                        width: 500,
                        height: 400,
                        destWidth: 500,
                        destHeight: 400,
                        success:function(res){
                            cfg.image_url = res.tempFilePath;
                            cfg.share_param = share_param;
                            if(isInit)
                                LBMH5.initWXShareConfig(cfg,_callback);
                            else
                                LBMH5.wxShare(cfg,_callback);
                        }
                    });
                }else{
                    cfg.image_url = image_url;
                    cfg.share_param = share_param;
                    if(isInit)
                        LBMH5.initWXShareConfig(cfg,callback);
                    else
                        LBMH5.wxShare(cfg,callback);
                }
            }
        }
		__proto.sendEventStatistics = function (name, data){
			if(wx.aldSendEvent)
				wx.aldSendEvent(name,{param:data});
		}
		__proto.onShow = function (data){
			console.log("onWxShow = "+JSON.stringify(data));
			//this.sendEventStatistics("shareOnShow",_cfg.share_param);
		}
        //微信转发
        __proto.wxShare = function (cfg, callback){
            var _callback = callback;
            var _cfg = cfg;
			var _result = {};
			var _this = this;
			var _shareFunction = wx.aldShareAppMessage ? wx.aldShareAppMessage : wx.shareAppMessage;
			wx.showShareMenu();
			wx.updateShareMenu({
				withShareTicket:true,
				success:function(data){
					_this.sendEventStatistics("sendShare",_cfg.share_param);
					_shareFunction({
						title:_cfg.title,
						imageUrl:_cfg.image_url,
						query:_cfg.share_param,
						success:function(data){
							console.log("--Share----updateShareMenu------success data = "+JSON.stringify(data));
							_result.state = 0;
							_result.data = data;
							_callback && _callback(_result);							
						},
						fail:function(data){
							console.log("--Share----updateShareMenu------fail----------");
							_result.state = 1;
							_result.data = data;
							_callback && _callback(_result);
							console.log(data);
						}						
					});
				},fail:function(data){
					console.log("--Share----updateShareMenu------fail----------");
					_result.state = 1;
					_result.data = data;
					_callback && _callback(_result);
					console.log(data);
				}
			});			
		}
		
        //微信默认转发配置
		__proto.initWXShareConfig = function (cfg, callback){
            var _callback = callback;
            var _cfg = cfg;
			var _this = this;
			var _shareFunction = wx.aldOnShareAppMeassage ? wx.aldOnShareAppMeassage : wx.onShareAppMessage;
			wx.showShareMenu();
			wx.updateShareMenu({
				withShareTicket:true,
				success:function(data){
					console.log("------updateShareMenu------success----------");
					console.log(data);
					_shareFunction(function(obj){
						console.log('onShareAppMessage');
						_this.sendEventStatistics("systemShare",_cfg.share_param);
						return {
							getGroupMsgTicket:true,
							title:_cfg.title,
							imageUrl:_cfg.image_url,
							query:_cfg.share_param,
							success:function(res){
								console.log(res);
								_callback && _callback(1)
							},
							fail:function(){
								_callback && _callback(0)
							}
						}
					});
				},fail:function(data){
					console.log("------updateShareMenu------fail----------");
					console.log(data);
				}
			});
		}

		//注销
        __proto.logout = function (param, callback) {
            
        };

		//充值
        __proto.recharge = function (param, callback) {
            
        };
        
        __proto.init = function(win,param, callback){
            if(param)
            {
                param = JSON.parse(param);
                if(param.openId && param.openKey)
                {
                    wnd.openId = param.openId;
                    wnd.openKey = param.openKey;
                }
                callback&&callback(JSON.stringify({"result":0}));
            }
        }
        
        LayaMakerMarket.instance = null;
        return LayaMakerMarket;
    })();
    wnd.LayaStorageH5 = (function () {
        function LayaStorageH5(storageName) {
            if (window.localStorage)
                this.store = window.localStorage;
            else
                this.store = {
                    //内存storage, 写入的localStorage临时存放在内存里，
                    //程序关闭后，数据消失，防止不支持localStorage的浏览器报错
                    "keys": [],
                    "values": [],
                    "setItem": function (key, value) {
                        var index = this.keys.indexOf(key);
                        if (index > -1)
                            this.values[index] = value;
                        else {
                            this.values.push(value);
                            this.keys.push(key);
                        }
                    },
                    "getItem": function (key) {
                        var index = this.keys.indexOf(key);
                        if (index > -1)
                            return this.values[index];
                        return null;
                    },
                    "removeItem": function (key) {
                        var index = this.keys.indexOf(key);
                        if (index > -1)
                            return this.values.splice(index, 1)[0];
                        return null;
                    },
                    "clear": function () {
                        this.values.length = 0;
                        this.keys.length = 0;
                    },
                    "key": function (index) {
                        return index < this.keys.length ? this.keys[index] : null;
                    },
                    "length": function () {
                        return this.keys.length;
                    }
                };
            this.storageName = storageName;
        }
        var __proto = LayaStorageH5.prototype;
        __proto.getItem = function (key) {
            var m_this = this;
            var storage = m_this.store.getItem(m_this.storageName) || '{}';
            var store = JSON.parse(storage);
            return store.hasOwnProperty(key) ? store[key] : null;
        };
        __proto.removeLocalStore = function (key) {
            var m_this = this;
            var storage = m_this.store.getItem(m_this.storageName) || '{}';
            var store = JSON.parse(storage);
            store.hasOwnProperty(key) && delete store[key];
            m_this.store.setItem(m_this.storageName, JSON.stringify(store));
        };
        __proto.clearLocalStore = function () {
            var m_this = this;
            m_this.store.setItem(m_this.storageName, '{}');
        };
        __proto.setItem = function (key, value) {
            var m_this = this;
            var storage = m_this.store.getItem(m_this.storageName) || '{}';
            var store = JSON.parse(storage);
            store[key] = value;
            m_this.store.setItem(m_this.storageName, JSON.stringify(store));
        };
        return LayaStorageH5;
    })();
    wnd.LayaCommon = (function () {
        function LayaCommon() {
        }
        LayaCommon.closeWnd = function (frameId) {
            var frame = document.getElementById(frameId);
            frame && document.body.removeChild(frame);
        };
        LayaCommon.openUrl = function (frameId, popupUrl, css) {
            var iframe = document.createElement("iframe");
            iframe.frameBorder = "0";
            iframe.scrolling = "auto";
            iframe.setAttribute("id", frameId);
            if (css) {
                var content = css;
                var style = document.createElement("style");
                style.innerHTML = content;
                style.setAttribute("id", frameId + "Style");
                document.head.appendChild(style);
            }
            else {
                iframe.style.position = "relative";
                iframe.style.left = "0px";
                iframe.style.top = "0px";
                iframe.style.height = "100%";
                iframe.style.width = "100%";
                iframe.style.zIndex = 9998;
                iframe.style.backgroundColor = "#ffffff";
            }
            iframe.src = popupUrl;
            document.body.appendChild(iframe);
        };
        LayaCommon.checkWeiXin = function () {
            var ua = window.navigator.userAgent.toLowerCase();
            return ua.match(/MicroMessenger/i) == "micromessenger";
        };
        LayaCommon.loadScript = function (url, onload, onerror) {
            var scp = document.createElement("script");
            scp.onload = function () {
                onload && onload({"result": 0});
            };
            scp.onerror = function () {
                onerror && onerror({"result": -100, "desc": "脚本下载失败"})
            };
            document.head.appendChild(scp);
            scp.src = url;
        };
        LayaCommon.getUniqueID = function (splitChar) {
            var uniqueID = "";
            for (var i = 1; i <= 32; i++) {
                uniqueID += Math.floor(Math.random() * 16.0).toString(16);
                if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                    uniqueID += (splitChar ? splitChar : "");
            }
            return uniqueID;
        };
        LayaCommon.createCallback = function (callback, callbackName) {
            if (!callbackName)
                callbackName = "callback" + LayaCommon.getUniqueID("_");
            window[callbackName] = (function (name) {
                function CallbackHandler(param) {
                    if (window[CallbackHandler.funcName]) {
                        window[CallbackHandler.funcName] = null;
                        delete window[CallbackHandler.funcName];
                    }
                    if (document && document.head) {
                        var scp = document.getElementById(CallbackHandler.funcName)
                        scp && document.head.removeChild(scp);
                    }
                    callback && callback(param);
                }

                CallbackHandler.funcName = name;
                return CallbackHandler;
            })(callbackName);
            return callbackName;
        };
        LayaCommon.getJson = function (url, callback, onError) {
            var callbackName = LayaCommon.createCallback(function (param) {
                if (param.ret != 0) {
                    LayaCommon.errorLog({type:"market","error_type":"LayaH5Market","url":url,"errorInfo": JSON.stringify(param)});
                }
                callback && callback(param);
            });
            var scp = document.createElement("script");
            document.head.appendChild(scp);
            scp.id = callbackName;
            scp.onerror = function () {
                if (url.indexOf("developer.layabox.com") == -1) {
                    LayaCommon.errorLog({type:"market","error_type":"LayaH5Market","url":url,"errorInfo": "Request Fail"});
                }
                onError && onError({"result": -101, "desc": "json download error"})
            };
            scp.src = (url.indexOf("?") > -1) ? (url + "&callback=" + callbackName) : (url + "?callback=" + callbackName);
        };
        LayaCommon.getPostJson = function (targetUrl, params, method, accessToken, callback) {
            var url = "//ucenter.layabox.com/HRProxy/http?url=" + targetUrl + "&params=" + params + "&ac=" + method + "&access_token=" + accessToken;
            LayaCommon.getJson(url, function (param) {
                callback && callback(param);
            }, function (param) {
                callback && callback(param);
            });
        };

        LayaCommon.errorLog = function(param){
            var str = [];
            for(var prop in param) {
                str.push(prop + "=" + encodeURIComponent(param[prop]));
            }
            str.push('errResourceUrl=' + encodeURIComponent(window.location.href));
            // LayaCommon.getJson(errorLogUrl + "?" + str.join("&"))
        }
        return LayaCommon;
    })();
    LayaMakerMarket.getInstance();
})(window);


